import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/input_option.dart';
import 'package:qunaimedical/components/item_add.dart';
import 'package:qunaimedical/components/item_image_preview.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

/// 上传报告界面
class CheckItemCreatePage extends StatefulWidget {
  final Patient item;

  const CheckItemCreatePage(this.item, {Key key}) : super(key: key);

  @override
  _CheckItemCreatePageState createState() => _CheckItemCreatePageState();
}

class _CheckItemCreatePageState extends State<CheckItemCreatePage> {
  String _time;

  /// 选中的图片
  List<Asset> _images = <Asset>[];

  /// 用户上传的图片路径
  List<String> _uploadedImages = [];

  /// 最多选9张图片
  int maxImageCount = 9;

  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加检查项'),
      ),
      body: ListView(
        padding: EdgeInsets.only(top: 10),
        children: [
          PrimaryLabel('检查项信息'),
          InputOption(
            label: '报告名称',
            hintText: '请输入报告名称',
            controller: _controller,
          ),
          TextOption(
            label: '检查时间',
            secondText: _time == null ? '请选择检查时间' : _time,
            secondTextColor: _time == null ? Colors.grey : Colors.black,
            onTap: _selectTime,
          ),
          CustomDivider(),
          PrimaryLabel(
            '添加图片',
            trailing: Text('${_images.length}/$maxImageCount'),
          ),
          Container(
            color: Colors.white,
            height: 110,
            width: double.maxFinite,
            alignment: Alignment.topLeft,
            padding: EdgeInsets.all(10),
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemBuilder: (c, i) {
                if (i == _images.length) {
                  return ItemAdd(onTap: _selectImages);
                } else {
                  return InkWell(
                    onTap: () {
                      CommonUtils.openGallery(
                          context,
                          _uploadedImages
                              .map((e) => Urls.BASE_URL + e)
                              .toList(),
                          i);
                    },
                    child: ItemImagePreview(
                      _images[i],
                      onTap: () {
                        // 删除图片时，判断已上传图片列表中是否包含这张照片。
                        if (_uploadedImages.length > i) {
                          _uploadedImages.removeAt(i);
                        }
                        setState(() {
                          _images.removeAt(i);
                        });
                      },
                    ),
                  );
                }
              },
              itemCount: _images.length == maxImageCount
                  ? _images.length
                  : _images.length + 1,
              padding: EdgeInsets.only(left: 0),
              separatorBuilder: (BuildContext context, int index) {
                // 给最后一个加号前面添加间距。
                return SizedBox(
                  width: _images.length > 0 && index == _images.length - 1
                      ? 13
                      : 0,
                );
              },
            ),
          ),
          PrimaryButton('报告', onPressed: _create),
        ],
      ),
    );
  }

  void _selectImages() async {
    CommonUtils.hideKeyboard(context);
    try {
      List<Asset> value = await MultiImagePicker.pickImages(
        maxImages: maxImageCount,
        selectedAssets: _images,
      );
      if (mounted) {
        setState(() {
          _images = value;
        });
        if (_images.isNotEmpty) {
          _uploadImages();
        }
      }
    } on Exception catch (e) {
      Log.i(e);
    }
  }

  void _selectTime() {
    CommonUtils.hideKeyboard(context);
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now().subtract(Duration(days: 365 * 10)),
        maxTime: DateTime.now(), onConfirm: (date) {
      setState(() {
        _time = date.toString().substring(0, 16);
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  /// 图片上传
  void _uploadImages() async {
    DialogUtils.showWaitDialog(context);
    FormData formData = FormData.fromMap({});
    formData.files.addAll((await CommonUtils.images2MapEntry(_images)));
    var value = await XHttp.uploadFiles(
      Urls.UPLOAD,
      formData,
    );
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _uploadedImages = List<String>.from(response.data);
      }
    }
    Navigator.pop(context);
  }

  void _create() async {
    CommonUtils.hideKeyboard(context);
    String content = _controller.text.trim();
    if (content.isEmpty) {
      ToastUtil.show('请输入报告名称', context);
      return;
    }
    if (_time == null) {
      ToastUtil.show('请选择检查时间', context);
      return;
    }
    if (_uploadedImages.isEmpty) {
      ToastUtil.show('请上传图片', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.CHECK_ITEM_ADD, {
      "doctorAccount": SPUtils.getUser().id,
      "patientAccount": widget.item.patiAccountId, //患者accountid
      "checkTime": _time, //检查时间
      "checkName": content,
      "enclosure": _uploadedImages.join(','), //图片路径
    });
    Navigator.pop(context);
    if (data != null) {
      var response = data as Map<String, dynamic>;
      if (response['success']) {
        Navigator.pop(context, true);
      } else {
        ToastUtil.show(response['msg'], context);
      }
    }
  }
}
